#include "infer.h"
#include <stdio.h>
#include <stdlib.h>

void read_inputfile (char *filename, struct infer *infer)
{
	FILE *fp;
	int i, N, L, M;

	fp = fopen (filename, "r");
	fscanf (fp, "%d %d", &N, &L);
	infer->N = N;

	infer->init = calloc (sizeof (int), N);
	for (i = 0; i < N; i++)
	{
		fscanf (fp, "%d", &(infer->init[i]));
		if (infer->init[i] != 0 && infer->init[i] != 1)
		{
			printf ("Node's status can only be 1(on) or 0(off)\n");
			exit (0);
		}
	}

	infer->flips = calloc (sizeof (int), N + 1);
	infer->flips[N] = 0;
	infer->maxL = 2;
	for (i = 0; i < N; i++)
	{
		fscanf (fp, "%d", &(infer->flips[i]));
		if (infer->trigger != 1 || i != 0)
			infer->maxL += infer->flips[i];
		if (infer->flips[N] < infer->flips[i])
			infer->flips[N] = infer->flips[i];
	}

	if (infer->trigger == 1)
	{
		if (infer->init[0] == 0 || infer->flips[0] != 1)
		{
			printf ("The first node in the inputfile is not the trigger node.\n");
			exit (0);
		}
	}

	if (infer->model == 0 || infer->model == 2)
	{
		infer->minL = infer->flips[N] + 2;
	}
	else if (infer->model == 1 || infer->model == 3)
	{
		infer->minL = 2 * infer->flips[N] + 1;
	}

	fscanf (fp, "%d", &M);

	infer->M = M;
	infer->timeorder = calloc (sizeof (timeorder), M);

	for (i = 0; i < M; i++)
	{
		fscanf (fp, "%d %d %d %d %d", &(infer->timeorder[i].n1), &(infer->timeorder[i].flip1), &(infer->timeorder[i].n2), &(infer->timeorder[i].flip2), &(infer->timeorder[i].type));
	}

	fclose (fp);
}

void print_pathway (int N, int L, int pathway[L][N])
{
	int i, j, num;

	num = 0;

	for (i = 0; i < L; i++)
	{
		for (j = 0; j < N; j++)
		{
			if (pathway[i][j] == -1)
				num ++;
		}
	}

	printf ("c Candidate Pathway %d %d\n", L, num);
	for (i = 0; i < L; i++)
	{
		for (j = 0; j < N; j++)
		{
			if (pathway[i][j] == -1)
				printf ("* ");
			else
				printf ("%d ", pathway[i][j]);
		}
		printf ("\n");
	}
}

int print_network (int N, int g[N][N], int r[N][N], int list[])
{
	int i, j, links;

	links = 0;
	for (i = 0; i < N; i++)
	{
		for (j = 0; j < N; j++)
		{
			if (list[r[i][j]] == 1 || list[g[i][j]] == 1)
				links ++;
		}
	}

	printf ("c Candidate Network %d\n", links);
	for (i = 0; i < N; i++)
	{
		for (j = 0; j < N; j++)
		{
			if (list[r[i][j]] == 1)
				printf ("r ");
			else if (list[g[i][j]] == 1)
				printf ("g ");
			else if (list[r[i][j]] == 0 && list[g[i][j]] == 0)
				printf ("n ");
			else if (list[g[i][j]] == 0)
				printf ("R ");
			else if (list[r[i][j]] == 0)
				printf ("G ");
			else
				printf ("* ");
		}
		printf ("\n");
	}

	return links;
}
